using System;

namespace Microsoft.Phone.Reactive
{
    /// <summary>
    /// Disposable task super-class.
    /// </summary>
    public abstract class DisposableTaskBase : IDisposable
    {
        private IDisposable _disposable;

        /// <summary>
        /// Gets or sets the disposable Task.
        /// </summary>
        protected IDisposable Task
        {
            get { return _disposable; }
            set { _disposable = value; }
        }

        /// <summary>
        /// .ctor
        /// </summary>
        /// <param name="scheduler"></param>
        protected DisposableTaskBase(IScheduler scheduler)
        {
            if (scheduler == null)
            {
                throw new ArgumentNullException("scheduler");
            }

            Scheduler = scheduler;
        }

        /// <summary>
        /// Gets <see cref="IScheduler">Scheduler</see> associated with task.
        /// </summary>
        protected IScheduler Scheduler { get; private set; }

        #region Implementation of IDisposable

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        /// <param name="disposing"></param>
        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (_disposable != null)
                {
                    _disposable.Dispose();
                    _disposable = null;
                }
            }
        }

        /// <summary>
        /// Allows an object to try to free resources and perform other cleanup operations before the <see cref="T:System.Object"/> is reclaimed by garbage collection.
        /// </summary>
        ~DisposableTaskBase()
        {
            Dispose(false);
        }

        #endregion
    }
}